package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 品牌--分页查询
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @param key
     * @return
     */
    public PageResult<Brand> pageQuery(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        // 查询总条数, 每页数据
        // 开启分页助手
        PageHelper.startPage(page, rows);
        // 过滤
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) {
            Example.Criteria criteria = example.createCriteria();
            criteria.andLike("name", "%" + key + "%");
        }
        if (StringUtils.isNotBlank(sortBy)) {
            example.setOrderByClause(sortBy + (desc ? " DESC" : " ASC"));
        }
        Page<Brand> brandPage = (Page<Brand>) brandMapper.selectByExample(example);
        PageResult<Brand> pageResult = new PageResult<Brand>(brandPage.getTotal(), new Long(brandPage.getPages()), brandPage.getResult());
        return pageResult;
    }

    /**
     * 品牌--新增
     * @param brand
     * @param cids
     */
    @Transactional // 事务管理
    public void addBrand(Brand brand, List<Long> cids) {
        // 新增品牌
        brandMapper.insertSelective(brand);
        // 中间表新增数据
        cids.forEach(cid -> {
            brandMapper.insertBrandCategory(brand.getId(), cid);
        });
    }

    /**
     * 品牌-更新
     * @param brand
     * @param cids
     */
    @Transactional
    public void updateBrand(Brand brand, List<Long> cids) {
        // 更新品牌信息
        brandMapper.updateByPrimaryKey(brand);
        // 删掉中间表的数据
        brandMapper.deleteBrandCategory(brand.getId());
        // 更新中间表的数据
        cids.forEach(cid -> {
            brandMapper.insertBrandCategory(brand.getId(), cid);
        });
    }

    public List<Brand> queryBrandByCategory(Long cid) {
        return brandMapper.queryBrandByCategory(cid);
    }

    public Brand queryBrandById(Long bid) {
        return brandMapper.selectByPrimaryKey(bid);
    }
}
